package com.sl.au.service.impl;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.persistence.Query;

import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.sl.au.entity.Attachment;
import com.sl.au.entity.AuditRoot;
import com.sl.au.entity.Contract;
import com.sl.au.entity.ContractCruxDate;
import com.sl.au.entity.ContractInfo;
import com.sl.au.entity.ContractPart;
import com.sl.au.entity.ContractPump;
import com.sl.au.entity.ContractRepair;
import com.sl.au.entity.ContractVo;
import com.sl.au.entity.Customer;
import com.sl.au.entity.CustomerMailingInfo;
import com.sl.au.entity.DetailRelevance;
import com.sl.au.entity.DivideScale;
import com.sl.au.entity.Quote;
import com.sl.au.entity.QuoteDevice;
import com.sl.au.entity.QuoteReplacement;
import com.sl.au.entity.Root;
import com.sl.au.entity.User;
import com.sl.au.repository.ContractCruxDateRepository;
import com.sl.au.repository.ContractInfoRepository;
import com.sl.au.repository.ContractPartRepository;
import com.sl.au.repository.ContractPumpRepository;
import com.sl.au.repository.ContractRepairRepository;
import com.sl.au.repository.ContractRepository;
import com.sl.au.repository.CustomerMailingInfoRepository;
import com.sl.au.repository.CustomerRepository;
import com.sl.au.repository.DetailRelevanceRepository;
import com.sl.au.repository.DeviceRepository;
import com.sl.au.repository.DivideScaleRepository;
import com.sl.au.repository.QuoteDeviceRepository;
import com.sl.au.repository.QuoteReplacementRepository;
import com.sl.au.repository.ReplacementDeviceRepository;
import com.sl.au.service.AttachmentService;
import com.sl.au.service.AuditNodeService;
import com.sl.au.service.ContractService;
import com.sl.au.service.DocService;
import com.sl.au.service.ExcelService;
import com.sl.au.service.QueryService;
import com.sl.utils.DataConverter;

/**
 * 合同管理接口
 * 
 * @author XH
 *
 */
@Service("ContractService")
@Transactional
public class ContractServiceImpl extends BaseServiceImpl implements ContractService {

	@Autowired
	ContractRepository contractRepository;
	
	@Autowired
	ContractInfoRepository contractInfoRepository;

	@Autowired
	DivideScaleRepository divideScaleRepository;

	@Autowired
	ContractPartRepository contractPartRepository;

	@Autowired
	ContractPumpRepository contractPumpRepository;

	@Autowired
	ContractRepairRepository contractRepairRepository;

	@Autowired
	QuoteDeviceRepository quoteDeviceRepository;

	@Autowired
	QuoteReplacementRepository quoteReplacementRepository;

	@Autowired
	DetailRelevanceRepository detailRelevanceRepository;

	@Autowired
	ReplacementDeviceRepository replacementDeviceRepository;

	@Autowired
	DeviceRepository deviceRepository;
	
	@Autowired
	ContractCruxDateRepository contractCruxDateRepository;

	@Autowired
	ExcelService excelService;
	
	@Autowired
	AuditNodeService auditNodeService;
	
	@Autowired
	AttachmentService attachmentService;
	
	@Autowired
	QueryService queryService;
	
	@Autowired
	CustomerRepository cusomertRepository;
	
	@Autowired
	CustomerMailingInfoRepository customerMailingInfoRepository;

	public ContractRepository getRepository() {
		return this.contractRepository;
	}
	
	public ContractInfoRepository getContractInfoRepository() {
		return this.contractInfoRepository;
	}

	public DivideScaleRepository getRepository1() {
		return this.divideScaleRepository;
	}

	public ContractPartRepository getRepository2() {
		return this.contractPartRepository;
	}

	public ContractPumpRepository getRepository3() {
		return this.contractPumpRepository;
	}

	public ContractRepairRepository getRepository4() {
		return this.contractRepairRepository;
	}

	public QuoteDeviceRepository getRepository5() {
		return this.quoteDeviceRepository;
	}

	public DetailRelevanceRepository getRepository6() {
		return this.detailRelevanceRepository;
	}

	public ReplacementDeviceRepository getRepository7() {
		return this.replacementDeviceRepository;
	}

	public DeviceRepository getRepository8() {
		return this.deviceRepository;
	}

	public QuoteReplacementRepository getRepository9() {
		return this.quoteReplacementRepository;
	}
	
	public ContractCruxDateRepository getRepository10() {
		return this.contractCruxDateRepository;
	}
	
	@Override
	public List<ContractInfo> getContractInfos(int start, int length, Map<String, String> condition, String orderName, String dir) {
		Page<ContractInfo> pages = null;
		String dataFilter = condition.get("dataFilter");
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
		if(dataFilter.equals("所有")){
			pages = contractRepository.getContractInfos(condition.get("key"), pageable);
		}else if(dataFilter.equals("本部门")){
			pages = contractRepository.getContractInfos(condition.get("key"), condition.get("superior"), pageable);
		}else if(dataFilter.equals("本片区")){
			pages = contractRepository.getContractInfos(condition.get("key"), condition.get("superior"), condition.get("areaName"),  pageable);
		}else if(dataFilter.equals("本人")){
			pages = contractRepository.getContractInfosByUser(condition.get("key"), condition.get("userId"), pageable);
		}
		return pages.getContent();
	}
	
	@Override
	public long getContractInfosCount(Map<String, String> condition) {
		String dataFilter = condition.get("dataFilter");
		if(dataFilter.equals("所有")){
			return this.contractRepository.getContractInfoCount(condition.get("key"));
		}else if(dataFilter.equals("本部门")){
			return this.contractRepository.getContractInfoCount(condition.get("key"), condition.get("superior"));
		}else if(dataFilter.equals("本片区")){
			return this.contractRepository.getContractInfoCount(condition.get("key"), condition.get("superior"), condition.get("areaName"));
		}else{
			return this.contractRepository.getContractInfoByUserCount(condition.get("key"), condition.get("userId"));
		}
	}
	
	@Override
	public List<ContractInfo> getContractInfosByCustomer(int start, int length, Map<String, String> condition, String orderName, String dir) {
		Page<ContractInfo> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
		pages = contractRepository.getContractInfosByCustomerId(condition.get("key"), condition.get("customerId"), pageable);
		return pages.getContent();
	}
	
	@Override
	public long getContractInfosByCustomerCount(Map<String, String> condition) {
		return this.contractRepository.getContractInfoByCustomerCount(condition.get("key"), condition.get("customerId"));
	}
	
	@Override
	public List<Contract> getContracts(int start, int length, String key, String orderName, String dir) {
		Page<Contract> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "id");
		pages = contractRepository.getContracts(key, pageable);
		return pages.getContent();
	}
	
	@Override
	public long getContractsCount(String key) {
		return this.contractRepository.getContractCount(key);
	}
	
	@Override
	public List<ContractCruxDate> getContractCruxDates(int start, int length, String contractId, String orderName, String dir) {
		Page<ContractCruxDate> pages = null;
		Pageable pageable = new PageRequest(start / length, length);
		pages = contractRepository.getContractCruxDates(contractId, pageable);
		return pages.getContent();
	}
	
	@Override
	public long getContractCruxDatesCount(String contractId) {
		return this.contractRepository.getContractCruxDateCount(contractId);
	}
	
	@Override
	public void saveContractCruxDate(ContractCruxDate contractCruxDate) {
		this.contractCruxDateRepository.save(contractCruxDate);
		updateContractCruxDate(contractCruxDate.getContractID(), contractCruxDate.getContractType());
	}
	
	@Override
	public void deleteContractCruxDate(String ids) {
		String[] cruxDateIds = ids.split(",");
		List<ContractCruxDate> cruxDates = new ArrayList<ContractCruxDate>();
		ContractCruxDate contractCruxDate = this.getRepository10().findOne(cruxDateIds[0]);
		String contractId = contractCruxDate.getContractID();
		String contractType = contractCruxDate.getContractType();
		for (String id : cruxDateIds){
			ContractCruxDate cruxDate = new ContractCruxDate();
			cruxDate.setId(id);
			cruxDates.add(cruxDate);
		}
		this.getRepository10().deleteInBatch(cruxDates);
		updateContractCruxDate(contractId, contractType);
	}
	
	/**
	 * 重新设置合同的三类关键日期
	 * @param contractId
	 * @param contractType
	 */
	public void updateContractCruxDate(String contractId, String contractType) {
		Date deliveryDate = null;
		Date debugDate = null;
		Date acceptanceDate = null;
		List<ContractCruxDate> ccds = contractRepository.getContractCruxDates(contractId);
		for (ContractCruxDate ccd : ccds) {
			if (deliveryDate==null&&ccd.getExecutiveType().equals("实际发货时间")){
				deliveryDate = ccd.getExecutiveDate();
			} else if (debugDate==null&&ccd.getExecutiveType().equals("调试完成时间")){
				debugDate = ccd.getExecutiveDate();
			} else if (acceptanceDate==null&&ccd.getExecutiveType().equals("验收完成时间")){
				acceptanceDate = ccd.getExecutiveDate();
			}
		}
		if (contractType.equals("项目合同")){
			Contract c = this.getRepository().findOne(contractId);
			c.setDeliveryDate(deliveryDate);
			c.setDebugDate(debugDate);
			c.setAcceptanceDate(acceptanceDate);
			this.getRepository().save(c);
		} else if (contractType.equals("备件合同")){
			ContractPart c = this.getRepository2().findOne(contractId);
			c.setDeliveryDate(deliveryDate);
			c.setDebugDate(debugDate);
			c.setAcceptanceDate(acceptanceDate);
			this.getRepository2().save(c);
		} else if (contractType.equals("备泵合同")){
			ContractPump c = this.getRepository3().findOne(contractId);
			c.setDeliveryDate(deliveryDate);
			c.setDebugDate(debugDate);
			c.setAcceptanceDate(acceptanceDate);
			this.getRepository3().save(c);
		} else if (contractType.equals("维修合同")){
			ContractRepair c = this.getRepository4().findOne(contractId);
			c.setDeliveryDate(deliveryDate);
			c.setDebugDate(debugDate);
			c.setAcceptanceDate(acceptanceDate);
			this.getRepository4().save(c);
		}
	}

	@Override
	public void deleteContract(String contractInfo) {
		// params[0]是contractId数据; params[1]是contractType数据
		String[] params = contractInfo.split(":");
		if (params.length == 2){
			String[] ids = params[0].split(",");
			String[] types = params[1].split(",");
			int i = 0;
			for (String id : ids){
				List<Attachment> attachments = new ArrayList<Attachment>();
				attachments = attachmentService.getRepository().findByParentId(id);
				attachmentService.getRepository().deleteInBatch(attachments);
				if (types[i].equals("项目合同")){
					boolean canDelete = true;//当前合同是否允许被删除
					if (canDelete){
						this.getRepository().deleteCruxDatesByContractId(id);
						this.getRepository().deleteDivideScalesByContractId(id);
						this.getRepository().deleteDevicesByContractId(id);
						this.getRepository().deleteReplacementsByContractId(id);
						this.getRepository().deleteRelevancesByContractId(id);
						this.getRepository().updateDeviceSupplierCodeByContractId(id);
						this.getRepository().updateReplacementSupplierCodeByContractId(id);
						this.getRepository().delete(id);
					}
				}else if (types[i].equals("备件合同")){
					this.getRepository().deleteCruxDatesByContractId(id);
					this.getRepository().deleteReplacementsByContractId(id);
					this.getRepository().deleteRelevancesByContractId(id);
					this.getRepository2().delete(id);
				}else if (types[i].equals("备泵合同")){
					this.getRepository().deleteCruxDatesByContractId(id);
					this.getRepository().deleteDevicesByContractId(id);
					this.getRepository().deleteRelevancesByContractId(id);
					this.getRepository3().delete(id);
				}else if (types[i].equals("维修合同")){
					this.getRepository().deleteCruxDatesByContractId(id);
					this.getRepository().deleteDevicesByContractId(id);
					this.getRepository().deleteReplacementsByContractId(id);
					this.getRepository().deleteRelevancesByContractId(id);
					this.getRepository4().delete(id);
				}
				i++;
			}
		}
	}
	
	@Override
	public List<User> getAllSuperiorMenBySuperior(String superior) {
		return this.contractRepository.getAllSuperiorMenBySuperior(superior);
	}
	
	@Override
	public List<Object> getSuperiorAreasBySuperior(String superior) {
		return this.contractRepository.getSuperiorAreasBySuperior(superior);
	}
	
	@Override
	public List<Object> getAreasBySuperior(String superior) {
		return this.contractRepository.getAreasBySuperior(superior);
	}
	
	@Override
	public List<Object> getDutyOfficersByroleName(String head, String deputyHead, String manager) {
		return this.contractRepository.getDutyOfficersByroleName(head, deputyHead, manager);
	}
	
	@Override
	public List<Object> getUserNamesByroleName(String roleName) {
		return this.contractRepository.getUserNamesByroleName(roleName);
	}
	
	@Override
	public Contract getContractById(String contractId) {
		return this.contractRepository.getContractById(contractId);
	}

	@Override
	public ContractPart getContractPartById(String contractId) {
		return this.contractRepository.getContractPartById(contractId);
	}

	@Override
	public ContractPump getContractPumpById(String contractId) {
		return this.contractRepository.getContractPumpById(contractId);
	}

	@Override
	public ContractRepair getContractRepairById(String contractId) {
		return this.contractRepository.getContractRepairById(contractId);
	}
	
	@Override
	public int getContractInfosCountBySupplierCode(String id, String code) {
		return this.contractRepository.getContractInfoCountBySupplierCode(id, code);
	}
	
	@Override
	public float getAllScaleDivide(String id) {
		float allScaleDivide = 0;
		List<Object> scaleDivides = this.contractRepository.getAllScaleDivide(id);
		for (Object scaleDivide:scaleDivides){
			allScaleDivide += (float) scaleDivide;
		}
		return allScaleDivide;
	}
	
	@Override
	public Map<String, Object> saveContract(Root root) {
		Map<String, Object> map = new HashMap<String, Object>();
		ContractInfo contractInfo = new ContractInfo();
		String contractId = "";
		String contractType = "";
		String supplierCode = "";
		Boolean isEdit = false;//是否是编辑,等于true时为编辑;
		if (root instanceof Contract) {
			Contract contract = (Contract) root;
			contractId = contract.getId();
			contractType = contract.getContractType();
			supplierCode = contract.getSupplierCode();
			Contract old = this.getRepository().findOne(contractId);
			if (old!=null){
				isEdit = true;
			}
			this.getRepository().save(contract);
		} else if (root instanceof ContractPart) {
			ContractPart contract = (ContractPart) root;
			contractId = contract.getId();
			contractType = contract.getContractType();
			supplierCode = contract.getSupplierCode();
			ContractPart old = this.getRepository2().findOne(contractId);
			if (old!=null){
				isEdit = true;
			}
			this.getRepository2().save(contract);
		} else if (root instanceof ContractPump) {
			ContractPump contract = (ContractPump) root;
			contractId = contract.getId();
			contractType = contract.getContractType();
			supplierCode = contract.getSupplierCode();
			ContractPump old = this.getRepository3().findOne(contractId);
			if (old!=null){
				isEdit = true;
			}
			this.getRepository3().save(contract);
		} else if (root instanceof ContractRepair) {
			ContractRepair contract = (ContractRepair) root;
			contractId = contract.getId();
			contractType = contract.getContractType();
			supplierCode = contract.getSupplierCode();
			ContractRepair old = this.getRepository4().findOne(contractId);
			if (old!=null){
				isEdit = true;
			}
			this.getRepository4().save(contract);
		}
		contractInfo.setContractId(contractId);
		contractInfo.setContractType(contractType);
		contractInfo.setSupplierCode(supplierCode);
		map.put("contractInfo", contractInfo);
		map.put("isEdit", isEdit);
		return map;
	}
	
	@Override
	public Contract getContractBySupplierCode(String supplierCode) {
		return this.contractRepository.getContractBySupplierCode(supplierCode);
	}
	
	@Override
	public List<DivideScale> getContractDivideScales(int start, int length, String contractId, String orderName,
			String dir) {
		Page<DivideScale> pages = null;
		Pageable pageable = new PageRequest(start / length, length);
		pages = contractRepository.getDivideScaleById(contractId, pageable);
		return pages.getContent();
	}

	@Override
	public long getContractDivideScalesCount(String contractId) {
		return this.contractRepository.getContractDivideScaleCount(contractId);
	}
	
	@Override
	public void deleteDivideScale(String ids) {
		String[] divideScaleIds = ids.split(",");
		List<DivideScale> divideScales = new ArrayList<DivideScale>();
		for (String id : divideScaleIds){
			DivideScale divideScale = new DivideScale();
			divideScale.setId(id);
			divideScales.add(divideScale);
		}
		this.getRepository1().deleteInBatch(divideScales);
	}

	@Override
	public List<Contract> getRelevanceContracts(int start, int length, String contractId, String orderName,
			String dir) {
		Page<Contract> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "id");
		pages = contractRepository.getRelevanceContractById(contractId, pageable);
		return pages.getContent();
	}
	
	@Override
	public long getRelevanceContractsCount(String contractId) {
		return this.contractRepository.getRelevanceContractByIdCount(contractId);
	}
	
	@Override
	public String getSupplierCodeByTypeAndId(String type, String id) {
		String code = "";
		if (type.equals("项目合同")){
			Contract oldC = this.getRepository().findOne(id);
			if (oldC!=null){
				code = oldC.getSupplierCode();
			}
		}else if (type.equals("备件合同")){
			ContractPart oldC = this.getRepository2().findOne(id);
			if (oldC!=null){
				code = oldC.getSupplierCode();
			}
		}else if (type.equals("备泵合同")){
			ContractPump oldC = this.getRepository3().findOne(id);
			if (oldC!=null){
				code = oldC.getSupplierCode();
			}
		}else if (type.equals("维修合同")){
			ContractRepair oldC = this.getRepository4().findOne(id);
			if (oldC!=null){
				code = oldC.getSupplierCode();
			}
		}
		return code;
	}
	
	@Override
	public List<QuoteDevice> getDevices(int start, int length, String contractId, String orderName, String dir) {
		Page<QuoteDevice> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "id");
		pages = contractRepository.getDeviceById(contractId, pageable);
		return pages.getContent();
	}
	
	@Override
	public long getDevicesCount(String contractId) {
		return this.contractRepository.getDeviceCountById(contractId);
	}
	
	@Override
	public void deleteDevice(String ids) {
		String[] quoteDeviceIds = ids.split(",");
		List<QuoteDevice> quoteDevices = new ArrayList<QuoteDevice>();
		for (String id : quoteDeviceIds) {
			QuoteDevice quoteDevice = new QuoteDevice();
			quoteDevice.setId(id);
			quoteDevices.add(quoteDevice);
			this.getRepository().deleteRelevancesBydetailId(id);
		}
		this.getRepository5().deleteInBatch(quoteDevices);
	}

	@Override
	public void editOneDevice(QuoteDevice quoteDevice) {
		Contract contract = null;
		//将暂时存在supplierCode中的选择关联的项目合同ID与合同号取出，得到对应的合同；
		if (quoteDevice.getSupplierCode()!=null){
			String[] params = quoteDevice.getSupplierCode().split(":");
			if (params.length == 2){
				if (StringUtils.hasText(params[0])){
					contract = contractRepository.findOne(params[0]);
				}else if(StringUtils.hasText(params[1])){
					contract = this.getContractBySupplierCode(params[1]);
				}
				String supplierCode = null;
				if (contract.getSupplierCode() != null && StringUtils.hasText(contract.getSupplierCode())) {
					supplierCode = contract.getSupplierCode();
				}
				quoteDevice.setSupplierCode(supplierCode);
			}
		}
		this.quoteDeviceRepository.save(quoteDevice);
		if (quoteDevice.getId() != null && StringUtils.hasText(quoteDevice.getId())) {
			this.contractRepository.deleteRelevancesBydetailId(quoteDevice.getId());
		}
		if (contract != null && contract.getId() != null) {
			DetailRelevance dr = new DetailRelevance();
			dr.setContractID(contract.getId());
			dr.setDetailID(quoteDevice.getId());
			dr.setDetailContractID(quoteDevice.getContractID());
			dr.setDetailContractType(quoteDevice.getContractType());
			this.detailRelevanceRepository.save(dr);
		}
	}

	@Override
	public void editMoreDevice(String deviceInfo) {
		String[] params = deviceInfo.split(":");// params[0]是id数据;
												// params[1]是需要关联的项目合同供方合同号
		if (params.length == 2) {
			String[] QuoteDeviceIds = params[0].split(",");
			String contractID = params[1];
			Contract contract = null;
			if (StringUtils.hasText(contractID)) {
				contract = contractRepository.findOne(contractID);
			}
			List<QuoteDevice> QuoteDevices = new ArrayList<QuoteDevice>();
			List<DetailRelevance> DetailRelevances = new ArrayList<DetailRelevance>();
			for (String id : QuoteDeviceIds) {
				QuoteDevice quoteDevice = this.quoteDeviceRepository.findOne(id);
				if (StringUtils.hasText(quoteDevice.getSupplierCode())) {
					this.contractRepository.deleteRelevancesBydetailId(quoteDevice.getId());
				}
				if (contract != null && contract.getId() != null && contract.getSupplierCode() != null) {
					quoteDevice.setSupplierCode(contract.getSupplierCode());
					DetailRelevance dr = new DetailRelevance();
					dr.setContractID(contract.getId());
					dr.setDetailID(quoteDevice.getId());
					dr.setDetailContractID(quoteDevice.getContractID());
					dr.setDetailContractType(quoteDevice.getContractType());
					QuoteDevices.add(quoteDevice);
					DetailRelevances.add(dr);
				} else {
					quoteDevice.setSupplierCode(null);
					QuoteDevices.add(quoteDevice);
				}
			}
			this.quoteDeviceRepository.save(QuoteDevices);
			this.detailRelevanceRepository.save(DetailRelevances);
		}
	}
	
	@Override
	public List<QuoteReplacement> getReplacements(int start, int length, String contractId, String orderName,
			String dir) {
		Page<QuoteReplacement> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.ASC, "indexOrder");
		pages = contractRepository.getReplacementById(contractId, pageable);
		return pages.getContent();
	}

	@Override
	public long getReplacementsCount(String contractId) {
		return this.contractRepository.getReplacementCountById(contractId);
	}
	
	@Override
	public void deleteReplacement(String ids) {
		String[] ReplacementDeviceIds = ids.split(",");
		List<QuoteReplacement> quoteReplacements = new ArrayList<QuoteReplacement>();
		for (String id : ReplacementDeviceIds){
			QuoteReplacement quoteReplacement = new QuoteReplacement();
			quoteReplacement.setId(id);
			quoteReplacements.add(quoteReplacement);
			this.getRepository().deleteRelevancesBydetailId(id);
		}
		this.getRepository9().deleteInBatch(quoteReplacements);
	}
	
	@Override
	public void editOneReplacement(QuoteReplacement quoteReplacement) {
		Contract contract = null;
		//将暂时存在supplierCode中的选择关联的项目合同ID与合同号取出，得到对应的合同；
		if (quoteReplacement.getSupplierCode()!=null){
			String[] params = quoteReplacement.getSupplierCode().split(":");
			if (params.length == 2){
				if (StringUtils.hasText(params[0])){
					contract = contractRepository.findOne(params[0]);
				}else if(StringUtils.hasText(params[1])){
					contract = this.getContractBySupplierCode(params[1]);
				}
				String supplierCode = null;
				if (contract.getSupplierCode() != null && StringUtils.hasText(contract.getSupplierCode())) {
					supplierCode = contract.getSupplierCode();
				}
				quoteReplacement.setSupplierCode(supplierCode);
			}
		}
		
		
		
		
		
		QuoteReplacement old=quoteReplacementRepository.findOne(quoteReplacement.getId());
		
		if(old!=null){
			
			if(old.getIndexOrder()!=quoteReplacement.getIndexOrder()){
				List<QuoteReplacement> rs=quoteReplacementRepository.findByContractIDAndIndexOrderGreaterThanEqualOrderByIndexOrderDesc(quoteReplacement.getContractID(),quoteReplacement.getIndexOrder());
				for(int i=0;i<rs.size();i++){
					int order=rs.get(i).getIndexOrder();
					rs.get(i).setIndexOrder(order+1);
				}
				quoteReplacementRepository.save(rs);
			}
			
			
			
		}else{
			
			if(quoteReplacement.getIndexOrder()==0){
				List<QuoteReplacement> ts=quoteReplacementRepository.findByContractIDOrderByIndexOrderDesc(quoteReplacement.getContractID());
				int index=ts.size()+1;
				if(!ts.isEmpty()){
					index=ts.get(0).getIndexOrder()+1;
				}
				quoteReplacement.setIndexOrder(index);
			}else {
				
				List<QuoteReplacement> rs=quoteReplacementRepository.findByContractIDAndIndexOrderGreaterThanEqualOrderByIndexOrderDesc(quoteReplacement.getContractID(),quoteReplacement.getIndexOrder());
				for(int i=0;i<rs.size();i++){
					int order=rs.get(i).getIndexOrder();
					rs.get(i).setIndexOrder(order+1);
				}
				quoteReplacementRepository.save(rs);
				
				
			}
			
			
			
		}
		
		
		
		
		
//		if(quoteReplacement.getIndexOrder()==0&&old==null){
//		}else if(old!=null&&old.getIndexOrder()!=quoteReplacement.getIndexOrder()){
//			
//			
//		}
//		
		
		
		
		
		this.quoteReplacementRepository.save(quoteReplacement);
		
		
		
		
		
		if (quoteReplacement.getId() != null && StringUtils.hasText(quoteReplacement.getId())) {
			this.contractRepository.deleteRelevancesBydetailId(quoteReplacement.getId());
		}
		if (contract != null && contract.getId() != null) {
			DetailRelevance dr = new DetailRelevance();
			dr.setContractID(contract.getId());
			dr.setDetailID(quoteReplacement.getId());
			dr.setDetailContractID(quoteReplacement.getContractID());
			dr.setDetailContractType(quoteReplacement.getContractType());
			this.detailRelevanceRepository.save(dr);
		}
	}

	@Override
	public void editMoreReplacement(String replacementInfo) {
		String[] params = replacementInfo.split(":");// params[0]是id数据;
														// params[1]是需要关联的项目合同供方合同号
		if (params.length == 2) {
			String[] QuoteReplacementIds = params[0].split(",");
			String contractID = params[1];
			Contract contract = null;
			if (StringUtils.hasText(contractID)) {
				contract = contractRepository.findOne(contractID);
			}
			List<QuoteReplacement> QuoteReplacements = new ArrayList<QuoteReplacement>();
			List<DetailRelevance> DetailRelevances = new ArrayList<DetailRelevance>();
			for (String id : QuoteReplacementIds) {
				QuoteReplacement quoteReplacement = this.quoteReplacementRepository.findOne(id);
				if (StringUtils.hasText(quoteReplacement.getSupplierCode())) {
					this.contractRepository.deleteRelevancesBydetailId(quoteReplacement.getId());
				}
				if (contract != null && contract.getId() != null && contract.getSupplierCode() != null) {
					quoteReplacement.setSupplierCode(contract.getSupplierCode());
					DetailRelevance dr = new DetailRelevance();
					dr.setContractID(contract.getId());
					dr.setDetailID(quoteReplacement.getId());
					dr.setDetailContractID(quoteReplacement.getContractID());
					dr.setDetailContractType(quoteReplacement.getContractType());
					QuoteReplacements.add(quoteReplacement);
					DetailRelevances.add(dr);
				} else {
					quoteReplacement.setSupplierCode(null);
					QuoteReplacements.add(quoteReplacement);
				}
			}
			this.quoteReplacementRepository.save(QuoteReplacements);
			this.detailRelevanceRepository.save(DetailRelevances);
		}
	}
	
	@SuppressWarnings("unchecked")
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public long importExcel(String fileName, String contractId, String type) {
		long count = 0;
		if (!StringUtils.hasText(fileName))
			return count;
		Map<String, Object> collections = new HashMap<>();
		// excelService.setStorageLocation(CRM.getStorageLocation());
		String entityName = "quoteReplacement";// 项目合同导入其他时用quoteReplacement.xml模版
		String contractType = "项目合同";
		if (type.equals("1")) {
			entityName = "quoteDevice";// 项目合同导入主机时用quoteDevice.xml模版
		} else if (type.equals("2")) {
			entityName = "quoteReplacementRepair";// 维修合同导入其他时用quoteReplacementRepair.xml模版
			contractType = "维修合同";
		} else if (type.equals("3")) {
			entityName = "quoteDeviceRepair";// 维修合同导入主机时用quoteDeviceRepair.xml模版
			contractType = "维修合同";
		} else if (type.equals("4")) {
			entityName = "quoteReplacementRepair";// 备件合同导入备件时用quoteReplacementRepair.xml模版(内容与维修合同其他一样)
			contractType = "备件合同";
		} else if (type.equals("5")) {
			entityName = "quoteDeviceRepair";// 备泵合同导入时用quoteDeviceRepair.xml模版(内容与维修合同主机一样)
			contractType = "备泵合同";
		}
		excelService.importExcel(entityName, collections, fileName);
		if (collections.size() < 1 || collections.get("items") == null)
			return count;
		if (type.equals("0") || type.equals("2") || type.equals("4")) {
			List<QuoteReplacement> rows = (List<QuoteReplacement>) collections.get("items");
			List<DetailRelevance> DetailRelevances = new ArrayList<DetailRelevance>();
			if (null != rows && rows.size() > 0) {
				for (QuoteReplacement quoteReplacement : rows) {
					quoteReplacement.setContractID(contractId);
					quoteReplacement.setContractType(contractType);
					if (quoteReplacement.getSupplierCode() != null && !quoteReplacement.getSupplierCode().equals("")) {
						String supplierCode = quoteReplacement.getSupplierCode();
						Contract contract = getContractBySupplierCode(supplierCode);
						if (contract != null) {
							DetailRelevance dr = new DetailRelevance();
							dr.setContractID(contract.getId());
							dr.setDetailID(quoteReplacement.getId());
							dr.setDetailContractID(contractId);
							dr.setDetailContractType(contractType);
							DetailRelevances.add(dr);
						} else {
							quoteReplacement.setSupplierCode(null);
						}
					}
				}
				this.quoteReplacementRepository.save(rows);
				this.detailRelevanceRepository.save(DetailRelevances);
				count = rows.size();
			}
		} else {
			List<QuoteDevice> rows = (List<QuoteDevice>) collections.get("items");
			List<DetailRelevance> DetailRelevances = new ArrayList<DetailRelevance>();
			if (null != rows && rows.size() > 0) {
				for (QuoteDevice quoteDevice : rows) {
					quoteDevice.setContractID(contractId);
					quoteDevice.setContractType(contractType);
					if (quoteDevice.getSupplierCode() != null && !quoteDevice.getSupplierCode().equals("")) {
						String supplierCode = quoteDevice.getSupplierCode();
						Contract contract = getContractBySupplierCode(supplierCode);
						if (contract != null) {
							DetailRelevance dr = new DetailRelevance();
							dr.setContractID(contract.getId());
							dr.setDetailID(quoteDevice.getId());
							dr.setDetailContractID(contractId);
							dr.setDetailContractType(contractType);
							DetailRelevances.add(dr);
						} else {
							quoteDevice.setSupplierCode(null);
						}
					}
				}
				this.quoteDeviceRepository.save(rows);
				this.detailRelevanceRepository.save(DetailRelevances);
				count = rows.size();
			}
		}
		return count;
	}
	
	
	
	
	

	@Override
	public List<Contract> getPage(int start, int length, String key, String orderName, String dir) {
		Page<Contract> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "id");
		pages = contractRepository.findAll(pageable);
		return pages.getContent();
	}

	@Override
	public List<Contract> getAfterSalePage(int start, int length, String key, String orderName, String dir) {
		Page<Contract> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "id");
		pages = contractRepository.getAfterSaleContracts1(pageable);
		return pages.getContent();
	}

	@Override
	public List<Contract> getAfterSaleContracts(int start, int length, String key, String orderName, String dir) {
		Page<Contract> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "id");
		pages = contractRepository.getAfterSaleContracts2(key, pageable);
		return pages.getContent();
	}

	@Override
	public List<Object> getContractSupplierCodeList() {
		return this.contractRepository.getContractSupplierCodeList();
	}
	
	@Override
	public List<QuoteDevice> getAllDetails(String contractId) {
		return this.contractRepository.getAllDetailById(contractId);
	}
	
	@Override
	public List<QuoteDevice> getDetails(String contractId, boolean b) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Map<String, Object> getContractVos(int start, int length, Map<String, String> condition, String orderName,
			String dir) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<ContractVo> ContractVos = new ArrayList<ContractVo>();
		/*
		 * ContractVos = this.contractRepository.getContractVos(key); Long count
		 * = (long) ContractVos.size(); resultMap.put("count", count);
		 */
		List<Contract> Contracts = null;
		List<ContractPart> ContractParts = null;
		List<ContractPump> ContractPumps = null;
		List<ContractRepair> ContractRepairs = null;
		int n = 0;// ContractVos中已有的数据条数;
		int i = 0;// 当前取值的位置,如i=23,且start为20,则当前在取第三页的第四条数据;
		Contracts = contractRepository.getContracts(condition.get("key"), condition.get("userId"));
		ContractParts = contractRepository.getContractParts(condition.get("key"), condition.get("userId"));
		ContractPumps = contractRepository.getContractPumps(condition.get("key"), condition.get("userId"));
		ContractRepairs = contractRepository.getContractRepairs(condition.get("key"), condition.get("userId"));
		Long count = (long) (Contracts.size() + ContractParts.size() + ContractPumps.size() + ContractRepairs.size());
		resultMap.put("count", count);
		if (Contracts.size() > start) {
			for (Contract contract : Contracts) {
				if (i >= start) {
					ContractVo contractVo = new ContractVo();
					contractVo = setContractVoData(contract);
					contractVo.setState(contract.getAuditState());
					ContractVos.add(contractVo);
					n++;
					if (n == length) {// 当ContractVos中条数达到当前分页规定的条数时,返回数据;
						resultMap.put("ContractVos", ContractVos);
						return resultMap;
					}
				}
				i++;
			}
		} else {
			i += Contracts.size();// 若当前类合同数据条数不能达到分页的起始条数，则将该类合同的数据条数累加到i上;
		}
		if ((ContractParts.size() + i) > start) {
			for (ContractPart contractPart : ContractParts) {
				if (i >= start) {
					ContractVo contractVo = new ContractVo();
					contractVo = setContractVoData(contractPart);
					contractVo.setState(contractPart.getAuditState());
					ContractVos.add(contractVo);
					n++;
					if (n == length) {
						resultMap.put("ContractVos", ContractVos);
						return resultMap;
					}
				}
				i++;
			}
		} else {
			i += ContractParts.size();
		}
		if ((ContractPumps.size() + i) > start) {
			for (ContractPump contractPump : ContractPumps) {
				if (i >= start) {
					ContractVo contractVo = new ContractVo();
					contractVo = setContractVoData(contractPump);
					contractVo.setState(contractPump.getAuditState());
					ContractVos.add(contractVo);
					n++;
					if (n == length) {
						resultMap.put("ContractVos", ContractVos);
						return resultMap;
					}
				}
				i++;
			}
		} else {
			i += ContractPumps.size();
		}
		if ((ContractRepairs.size() + i) > 0) {
			for (ContractRepair contractRepair : ContractRepairs) {
				if (i >= start) {
					ContractVo contractVo = new ContractVo();
					contractVo = setContractVoData(contractRepair);
					contractVo.setState(contractRepair.getAuditState());
					ContractVos.add(contractVo);
					n++;
					if (n == length) {
						resultMap.put("ContractVos", ContractVos);
						return resultMap;
					}
				}
				i++;
			}
		}

		resultMap.put("ContractVos", ContractVos);
		return resultMap;
	}

	@Override
	public Map<String, Object> getContractVos(int start, int length, String key, String orderName, String dir) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<ContractVo> ContractVos = new ArrayList<ContractVo>();
		/*
		 * ContractVos = this.contractRepository.getContractVos(key); Long count
		 * = (long) ContractVos.size(); resultMap.put("count", count);
		 */
		List<Contract> Contracts = null;
		List<ContractPart> ContractParts = null;
		List<ContractPump> ContractPumps = null;
		List<ContractRepair> ContractRepairs = null;
		int n = 0;// ContractVos中已有的数据条数;
		int i = 0;// 当前取值的位置,如i=23,且start为20,则当前在取第三页的第四条数据;
		Contracts = contractRepository.getContracts(key);
		ContractParts = contractRepository.getContractParts(key);
		ContractPumps = contractRepository.getContractPumps(key);
		ContractRepairs = contractRepository.getContractRepairs(key);
		Long count = (long) (Contracts.size() + ContractParts.size() + ContractPumps.size() + ContractRepairs.size());
		resultMap.put("count", count);
		if (Contracts.size() > start) {
			for (Contract contract : Contracts) {
				if (i >= start) {
					ContractVo contractVo = new ContractVo();
					contractVo = setContractVoData(contract);
					contractVo.setState(contract.getAuditState());
					ContractVos.add(contractVo);
					n++;
					if (n == length) {// 当ContractVos中条数达到当前分页规定的条数时,返回数据;
						resultMap.put("ContractVos", ContractVos);
						return resultMap;
					}
				}
				i++;
			}
		} else {
			i += Contracts.size();// 若当前类合同数据条数不能达到分页的起始条数，则将该类合同的数据条数累加到i上;
		}
		if ((ContractParts.size() + i) > start) {
			for (ContractPart contractPart : ContractParts) {
				if (i >= start) {
					ContractVo contractVo = new ContractVo();
					contractVo = setContractVoData(contractPart);
					contractVo.setState(contractPart.getAuditState());
					ContractVos.add(contractVo);
					n++;
					if (n == length) {
						resultMap.put("ContractVos", ContractVos);
						return resultMap;
					}
				}
				i++;
			}
		} else {
			i += ContractParts.size();
		}
		if ((ContractPumps.size() + i) > start) {
			for (ContractPump contractPump : ContractPumps) {
				if (i >= start) {
					ContractVo contractVo = new ContractVo();
					contractVo = setContractVoData(contractPump);
					contractVo.setState(contractPump.getAuditState());
					ContractVos.add(contractVo);
					n++;
					if (n == length) {
						resultMap.put("ContractVos", ContractVos);
						return resultMap;
					}
				}
				i++;
			}
		} else {
			i += ContractPumps.size();
		}
		if ((ContractRepairs.size() + i) > 0) {
			for (ContractRepair contractRepair : ContractRepairs) {
				if (i >= start) {
					ContractVo contractVo = new ContractVo();
					contractVo = setContractVoData(contractRepair);
					contractVo.setState(contractRepair.getAuditState());
					ContractVos.add(contractVo);
					n++;
					if (n == length) {
						resultMap.put("ContractVos", ContractVos);
						return resultMap;
					}
				}
				i++;
			}
		}

		resultMap.put("ContractVos", ContractVos);
		return resultMap;
	}

	private ContractVo setContractVoData(Contract contract) {
		ContractVo contractVo = new ContractVo();
		if (StringUtils.hasText(contract.getId())) {
			contractVo.setContractId(contract.getId());
		}
		if (contract.getCreateTime() != null) {
			contractVo.setCreateTime(contract.getCreateTime());
		}
		if (StringUtils.hasText(contract.getSupplierCode())) {
			contractVo.setSupplierCode(contract.getSupplierCode());
		}
		if (StringUtils.hasText(contract.getDemanderCode())) {
			contractVo.setDemanderCode(contract.getDemanderCode());
		}
		if (StringUtils.hasText(contract.getContractType())) {
			contractVo.setContractType(contract.getContractType());
		}
		contractVo.setTotalSum(contract.getTotalSum());
		if (contract.getSignedDate() != null) {
			contractVo.setSignedDate(contract.getSignedDate());
		}
		if (contract.getScheduleDate() != null) {
			contractVo.setScheduleDate(contract.getScheduleDate());
		}
		if (contract.getDeliveryDate() != null) {
			contractVo.setDeliveryDate(contract.getDeliveryDate());
		}
		if (StringUtils.hasText(contract.getStop())) {
			contractVo.setStop(contract.getStop());
		}
		contractVo.setFreightCharge(contract.getFreightCharge());
		if (StringUtils.hasText(contract.getProjectName())) {
			contractVo.setProjectName(contract.getProjectName());
		}
		if (StringUtils.hasText(contract.getPayType())) {
			contractVo.setPayType(contract.getPayType());
		}
		if (StringUtils.hasText(contract.getGuaranteePeriod())) {
			contractVo.setGuaranteePeriod(contract.getGuaranteePeriod());
		}
		if (StringUtils.hasText(contract.getBreakDuty())) {
			contractVo.setBreakDuty(contract.getBreakDuty());
		}
		if (StringUtils.hasText(contract.getOrderUnit())) {
			contractVo.setOrderUnit(contract.getOrderUnit());
		}
		if (StringUtils.hasText(contract.getOrderDelegate())) {
			contractVo.setOrderDelegate(contract.getOrderDelegate());
		}
		if (StringUtils.hasText(contract.getOrderPhone())) {
			contractVo.setOrderPhone(contract.getOrderPhone());
		}
		if (StringUtils.hasText(contract.getIndustryInfo())) {
			contractVo.setIndustryInfo(contract.getIndustryInfo());
		}
		if (StringUtils.hasText(contract.getOrderAddress())) {
			contractVo.setOrderAddress(contract.getOrderAddress());
		}
		contractVo.setOrderZip(contract.getOrderZip());
		if (StringUtils.hasText(contract.getOrderArea())) {
			contractVo.setOrderArea(contract.getOrderArea());
		}
		if (StringUtils.hasText(contract.getPostUnit())) {
			contractVo.setPostUnit(contract.getPostUnit());
		}
		if (StringUtils.hasText(contract.getPostDelegate())) {
			contractVo.setPostDelegate(contract.getPostDelegate());
		}
		if (StringUtils.hasText(contract.getPostPhone())) {
			contractVo.setPostPhone(contract.getPostPhone());
		}
		if (StringUtils.hasText(contract.getPostAddress())) {
			contractVo.setPostAddress(contract.getPostAddress());
		}
		contractVo.setPostZip(contract.getPostZip());
		if (StringUtils.hasText(contract.getDutyArea())) {
			contractVo.setDutyArea(contract.getDutyArea());
		}
		if (StringUtils.hasText(contract.getDutyOfficer())) {
			contractVo.setDutyOfficer(contract.getDutyOfficer());
		}
		if (StringUtils.hasText(contract.getSouthNorthArea())) {
			contractVo.setSouthNorthArea(contract.getSouthNorthArea());
		}
		if (StringUtils.hasText(contract.getBelongArea())) {
			contractVo.setBelongArea(contract.getBelongArea());
		}
		if (StringUtils.hasText(contract.getCheckKind())) {
			contractVo.setCheckKind(contract.getCheckKind());
		}
		if (StringUtils.hasText(contract.getProductKind())) {
			contractVo.setProductKind(contract.getProductKind());
		}
		if (StringUtils.hasText(contract.getSignOfficer())) {
			contractVo.setSignOfficer(contract.getSignOfficer());
		}
		if (StringUtils.hasText(contract.getRepairOfficer())) {
			contractVo.setRepairOfficer(contract.getRepairOfficer());
		}
		if (StringUtils.hasText(contract.getQuotationOfficer())) {
			contractVo.setQuotationOfficer(contract.getQuotationOfficer());
		}
		if (StringUtils.hasText(contract.getOperatDepartment())) {
			contractVo.setOperatDepartment(contract.getOperatDepartment());
		}
		if (StringUtils.hasText(contract.getOperator())) {
			contractVo.setOperator(contract.getOperator());
		}
		if (contract.getOperatDate() != null) {
			contractVo.setOperatDate(contract.getOperatDate());
		}
		if (StringUtils.hasText(contract.getMemo())) {
			contractVo.setMemo(contract.getMemo());
		}
		if (StringUtils.hasText(contract.getName())) {
			contractVo.setName(contract.getName());
		}
		if (StringUtils.hasText(contract.getProjectCode())) {
			contractVo.setProjectCode(contract.getProjectCode());
		}
		if (StringUtils.hasText(contract.getRepairCode())) {
			contractVo.setRepairCode(contract.getRepairCode());
		}
		contractVo.setRepairNumber(contract.getRepairNumber());
		if (StringUtils.hasText(contract.getRepairKind())) {
			contractVo.setRepairKind(contract.getRepairKind());
		}
		if (StringUtils.hasText(contract.getRepairKind())) {
			contractVo.setRepairKind(contract.getRepairKind());
		}
		if (contract.getRepairDate() != null) {
			contractVo.setRepairDate(contract.getRepairDate());
		}
		return contractVo;
	}

	private ContractVo setContractVoData(ContractPart contract) {
		ContractVo contractVo = new ContractVo();
		if (StringUtils.hasText(contract.getId())) {
			contractVo.setContractId(contract.getId());
		}
		if (contract.getCreateTime() != null) {
			contractVo.setCreateTime(contract.getCreateTime());
		}
		if (StringUtils.hasText(contract.getSupplierCode())) {
			contractVo.setSupplierCode(contract.getSupplierCode());
		}
		if (StringUtils.hasText(contract.getDemanderCode())) {
			contractVo.setDemanderCode(contract.getDemanderCode());
		}
		if (StringUtils.hasText(contract.getContractType())) {
			contractVo.setContractType(contract.getContractType());
		}
		contractVo.setTotalSum(contract.getTotalSum());
		if (contract.getSignedDate() != null) {
			contractVo.setSignedDate(contract.getSignedDate());
		}
		if (contract.getScheduleDate() != null) {
			contractVo.setScheduleDate(contract.getScheduleDate());
		}
		if (contract.getDeliveryDate() != null) {
			contractVo.setDeliveryDate(contract.getDeliveryDate());
		}
		if (StringUtils.hasText(contract.getStop())) {
			contractVo.setStop(contract.getStop());
		}
		contractVo.setFreightCharge((float)contract.getFreightCharge());
		if (StringUtils.hasText(contract.getProjectName())) {
			contractVo.setProjectName(contract.getProjectName());
		}
		if (StringUtils.hasText(contract.getPayType())) {
			contractVo.setPayType(contract.getPayType());
		}
		if (StringUtils.hasText(contract.getGuaranteePeriod())) {
			contractVo.setGuaranteePeriod(contract.getGuaranteePeriod());
		}
		if (StringUtils.hasText(contract.getBreakDuty())) {
			contractVo.setBreakDuty(contract.getBreakDuty());
		}
		if (StringUtils.hasText(contract.getOrderUnit())) {
			contractVo.setOrderUnit(contract.getOrderUnit());
		}
		if (StringUtils.hasText(contract.getOrderDelegate())) {
			contractVo.setOrderDelegate(contract.getOrderDelegate());
		}
		if (StringUtils.hasText(contract.getOrderPhone())) {
			contractVo.setOrderPhone(contract.getOrderPhone());
		}
		if (StringUtils.hasText(contract.getIndustryInfo())) {
			contractVo.setIndustryInfo(contract.getIndustryInfo());
		}
		if (StringUtils.hasText(contract.getOrderAddress())) {
			contractVo.setOrderAddress(contract.getOrderAddress());
		}
		contractVo.setOrderZip(contract.getOrderZip());
		if (StringUtils.hasText(contract.getOrderArea())) {
			contractVo.setOrderArea(contract.getOrderArea());
		}
		if (StringUtils.hasText(contract.getPostUnit())) {
			contractVo.setPostUnit(contract.getPostUnit());
		}
		if (StringUtils.hasText(contract.getPostDelegate())) {
			contractVo.setPostDelegate(contract.getPostDelegate());
		}
		if (StringUtils.hasText(contract.getPostPhone())) {
			contractVo.setPostPhone(contract.getPostPhone());
		}
		if (StringUtils.hasText(contract.getPostAddress())) {
			contractVo.setPostAddress(contract.getPostAddress());
		}
		contractVo.setPostZip(contract.getPostZip());
		if (StringUtils.hasText(contract.getDutyArea())) {
			contractVo.setDutyArea(contract.getDutyArea());
		}
		if (StringUtils.hasText(contract.getDutyOfficer())) {
			contractVo.setDutyOfficer(contract.getDutyOfficer());
		}
		if (StringUtils.hasText(contract.getSouthNorthArea())) {
			contractVo.setSouthNorthArea(contract.getSouthNorthArea());
		}
		if (StringUtils.hasText(contract.getBelongArea())) {
			contractVo.setBelongArea(contract.getBelongArea());
		}
		if (StringUtils.hasText(contract.getCheckKind())) {
			contractVo.setCheckKind(contract.getCheckKind());
		}
		if (StringUtils.hasText(contract.getProductKind())) {
			contractVo.setProductKind(contract.getProductKind());
		}
		if (StringUtils.hasText(contract.getSignOfficer())) {
			contractVo.setSignOfficer(contract.getSignOfficer());
		}
		if (StringUtils.hasText(contract.getRepairOfficer())) {
			contractVo.setRepairOfficer(contract.getRepairOfficer());
		}
		if (StringUtils.hasText(contract.getQuotationOfficer())) {
			contractVo.setQuotationOfficer(contract.getQuotationOfficer());
		}
		if (StringUtils.hasText(contract.getOperatDepartment())) {
			contractVo.setOperatDepartment(contract.getOperatDepartment());
		}
		if (StringUtils.hasText(contract.getOperator())) {
			contractVo.setOperator(contract.getOperator());
		}
		if (contract.getOperatDate() != null) {
			contractVo.setOperatDate(contract.getOperatDate());
		}
		if (StringUtils.hasText(contract.getMemo())) {
			contractVo.setMemo(contract.getMemo());
		}
		if (StringUtils.hasText(contract.getName())) {
			contractVo.setName(contract.getName());
		}
		if (StringUtils.hasText(contract.getProjectCode())) {
			contractVo.setProjectCode(contract.getProjectCode());
		}
		if (StringUtils.hasText(contract.getRepairCode())) {
			contractVo.setRepairCode(contract.getRepairCode());
		}
		contractVo.setRepairNumber(contract.getRepairNumber());
		if (StringUtils.hasText(contract.getRepairKind())) {
			contractVo.setRepairKind(contract.getRepairKind());
		}
		if (StringUtils.hasText(contract.getRepairKind())) {
			contractVo.setRepairKind(contract.getRepairKind());
		}
		if (contract.getRepairDate() != null) {
			contractVo.setRepairDate(contract.getRepairDate());
		}
		return contractVo;
	}

	private ContractVo setContractVoData(ContractPump contract) {
		ContractVo contractVo = new ContractVo();
		if (StringUtils.hasText(contract.getId())) {
			contractVo.setContractId(contract.getId());
		}
		if (contract.getCreateTime() != null) {
			contractVo.setCreateTime(contract.getCreateTime());
		}
		if (StringUtils.hasText(contract.getSupplierCode())) {
			contractVo.setSupplierCode(contract.getSupplierCode());
		}
		if (StringUtils.hasText(contract.getDemanderCode())) {
			contractVo.setDemanderCode(contract.getDemanderCode());
		}
		if (StringUtils.hasText(contract.getContractType())) {
			contractVo.setContractType(contract.getContractType());
		}
		contractVo.setTotalSum(contract.getTotalSum());
		if (contract.getSignedDate() != null) {
			contractVo.setSignedDate(contract.getSignedDate());
		}
		if (contract.getScheduleDate() != null) {
			contractVo.setScheduleDate(contract.getScheduleDate());
		}
		if (contract.getDeliveryDate() != null) {
			contractVo.setDeliveryDate(contract.getDeliveryDate());
		}
		if (StringUtils.hasText(contract.getStop())) {
			contractVo.setStop(contract.getStop());
		}
		contractVo.setFreightCharge(contract.getFreightCharge());
		if (StringUtils.hasText(contract.getProjectName())) {
			contractVo.setProjectName(contract.getProjectName());
		}
		if (StringUtils.hasText(contract.getPayType())) {
			contractVo.setPayType(contract.getPayType());
		}
		if (StringUtils.hasText(contract.getGuaranteePeriod())) {
			contractVo.setGuaranteePeriod(contract.getGuaranteePeriod());
		}
		if (StringUtils.hasText(contract.getBreakDuty())) {
			contractVo.setBreakDuty(contract.getBreakDuty());
		}
		if (StringUtils.hasText(contract.getOrderUnit())) {
			contractVo.setOrderUnit(contract.getOrderUnit());
		}
		if (StringUtils.hasText(contract.getOrderDelegate())) {
			contractVo.setOrderDelegate(contract.getOrderDelegate());
		}
		if (StringUtils.hasText(contract.getOrderPhone())) {
			contractVo.setOrderPhone(contract.getOrderPhone());
		}
		if (StringUtils.hasText(contract.getIndustryInfo())) {
			contractVo.setIndustryInfo(contract.getIndustryInfo());
		}
		if (StringUtils.hasText(contract.getOrderAddress())) {
			contractVo.setOrderAddress(contract.getOrderAddress());
		}
		contractVo.setOrderZip(contract.getOrderZip());
		if (StringUtils.hasText(contract.getOrderArea())) {
			contractVo.setOrderArea(contract.getOrderArea());
		}
		if (StringUtils.hasText(contract.getPostUnit())) {
			contractVo.setPostUnit(contract.getPostUnit());
		}
		if (StringUtils.hasText(contract.getPostDelegate())) {
			contractVo.setPostDelegate(contract.getPostDelegate());
		}
		if (StringUtils.hasText(contract.getPostPhone())) {
			contractVo.setPostPhone(contract.getPostPhone());
		}
		if (StringUtils.hasText(contract.getPostAddress())) {
			contractVo.setPostAddress(contract.getPostAddress());
		}
		contractVo.setPostZip(contract.getPostZip());
		if (StringUtils.hasText(contract.getDutyArea())) {
			contractVo.setDutyArea(contract.getDutyArea());
		}
		if (StringUtils.hasText(contract.getDutyOfficer())) {
			contractVo.setDutyOfficer(contract.getDutyOfficer());
		}
		if (StringUtils.hasText(contract.getSouthNorthArea())) {
			contractVo.setSouthNorthArea(contract.getSouthNorthArea());
		}
		if (StringUtils.hasText(contract.getBelongArea())) {
			contractVo.setBelongArea(contract.getBelongArea());
		}
		if (StringUtils.hasText(contract.getCheckKind())) {
			contractVo.setCheckKind(contract.getCheckKind());
		}
		if (StringUtils.hasText(contract.getProductKind())) {
			contractVo.setProductKind(contract.getProductKind());
		}
		if (StringUtils.hasText(contract.getSignOfficer())) {
			contractVo.setSignOfficer(contract.getSignOfficer());
		}
		if (StringUtils.hasText(contract.getRepairOfficer())) {
			contractVo.setRepairOfficer(contract.getRepairOfficer());
		}
		if (StringUtils.hasText(contract.getQuotationOfficer())) {
			contractVo.setQuotationOfficer(contract.getQuotationOfficer());
		}
		if (StringUtils.hasText(contract.getOperatDepartment())) {
			contractVo.setOperatDepartment(contract.getOperatDepartment());
		}
		if (StringUtils.hasText(contract.getOperator())) {
			contractVo.setOperator(contract.getOperator());
		}
		if (contract.getOperatDate() != null) {
			contractVo.setOperatDate(contract.getOperatDate());
		}
		if (StringUtils.hasText(contract.getMemo())) {
			contractVo.setMemo(contract.getMemo());
		}
		if (StringUtils.hasText(contract.getName())) {
			contractVo.setName(contract.getName());
		}
		if (StringUtils.hasText(contract.getProjectCode())) {
			contractVo.setProjectCode(contract.getProjectCode());
		}
		if (StringUtils.hasText(contract.getRepairCode())) {
			contractVo.setRepairCode(contract.getRepairCode());
		}
		contractVo.setRepairNumber(contract.getRepairNumber());
		if (StringUtils.hasText(contract.getRepairKind())) {
			contractVo.setRepairKind(contract.getRepairKind());
		}
		if (StringUtils.hasText(contract.getRepairKind())) {
			contractVo.setRepairKind(contract.getRepairKind());
		}
		if (contract.getRepairDate() != null) {
			contractVo.setRepairDate(contract.getRepairDate());
		}
		return contractVo;
	}

	private ContractVo setContractVoData(ContractRepair contract) {
		ContractVo contractVo = new ContractVo();
		if (StringUtils.hasText(contract.getId())) {
			contractVo.setContractId(contract.getId());
		}
		if (contract.getCreateTime() != null) {
			contractVo.setCreateTime(contract.getCreateTime());
		}
		if (StringUtils.hasText(contract.getSupplierCode())) {
			contractVo.setSupplierCode(contract.getSupplierCode());
		}
		if (StringUtils.hasText(contract.getDemanderCode())) {
			contractVo.setDemanderCode(contract.getDemanderCode());
		}
		if (StringUtils.hasText(contract.getContractType())) {
			contractVo.setContractType(contract.getContractType());
		}
		contractVo.setTotalSum(contract.getTotalSum());
		if (contract.getSignedDate() != null) {
			contractVo.setSignedDate(contract.getSignedDate());
		}
		if (contract.getScheduleDate() != null) {
			contractVo.setScheduleDate(contract.getScheduleDate());
		}
		if (contract.getDeliveryDate() != null) {
			contractVo.setDeliveryDate(contract.getDeliveryDate());
		}
		if (StringUtils.hasText(contract.getStop())) {
			contractVo.setStop(contract.getStop());
		}
		contractVo.setFreightCharge(contract.getFreightCharge());
		if (StringUtils.hasText(contract.getProjectName())) {
			contractVo.setProjectName(contract.getProjectName());
		}
		if (StringUtils.hasText(contract.getPayType())) {
			contractVo.setPayType(contract.getPayType());
		}
		if (StringUtils.hasText(contract.getGuaranteePeriod())) {
			contractVo.setGuaranteePeriod(contract.getGuaranteePeriod());
		}
		if (StringUtils.hasText(contract.getBreakDuty())) {
			contractVo.setBreakDuty(contract.getBreakDuty());
		}
		if (StringUtils.hasText(contract.getOrderUnit())) {
			contractVo.setOrderUnit(contract.getOrderUnit());
		}
		if (StringUtils.hasText(contract.getOrderDelegate())) {
			contractVo.setOrderDelegate(contract.getOrderDelegate());
		}
		if (StringUtils.hasText(contract.getOrderPhone())) {
			contractVo.setOrderPhone(contract.getOrderPhone());
		}
		if (StringUtils.hasText(contract.getIndustryInfo())) {
			contractVo.setIndustryInfo(contract.getIndustryInfo());
		}
		if (StringUtils.hasText(contract.getOrderAddress())) {
			contractVo.setOrderAddress(contract.getOrderAddress());
		}
		contractVo.setOrderZip(contract.getOrderZip());
		if (StringUtils.hasText(contract.getOrderArea())) {
			contractVo.setOrderArea(contract.getOrderArea());
		}
		if (StringUtils.hasText(contract.getPostUnit())) {
			contractVo.setPostUnit(contract.getPostUnit());
		}
		if (StringUtils.hasText(contract.getPostDelegate())) {
			contractVo.setPostDelegate(contract.getPostDelegate());
		}
		if (StringUtils.hasText(contract.getPostPhone())) {
			contractVo.setPostPhone(contract.getPostPhone());
		}
		if (StringUtils.hasText(contract.getPostAddress())) {
			contractVo.setPostAddress(contract.getPostAddress());
		}
		contractVo.setPostZip(contract.getPostZip());
		if (StringUtils.hasText(contract.getDutyArea())) {
			contractVo.setDutyArea(contract.getDutyArea());
		}
		if (StringUtils.hasText(contract.getDutyOfficer())) {
			contractVo.setDutyOfficer(contract.getDutyOfficer());
		}
		if (StringUtils.hasText(contract.getSouthNorthArea())) {
			contractVo.setSouthNorthArea(contract.getSouthNorthArea());
		}
		if (StringUtils.hasText(contract.getBelongArea())) {
			contractVo.setBelongArea(contract.getBelongArea());
		}
		if (StringUtils.hasText(contract.getCheckKind())) {
			contractVo.setCheckKind(contract.getCheckKind());
		}
		if (StringUtils.hasText(contract.getProductKind())) {
			contractVo.setProductKind(contract.getProductKind());
		}
		if (StringUtils.hasText(contract.getSignOfficer())) {
			contractVo.setSignOfficer(contract.getSignOfficer());
		}
		if (StringUtils.hasText(contract.getRepairOfficer())) {
			contractVo.setRepairOfficer(contract.getRepairOfficer());
		}
		if (StringUtils.hasText(contract.getQuotationOfficer())) {
			contractVo.setQuotationOfficer(contract.getQuotationOfficer());
		}
		if (StringUtils.hasText(contract.getOperatDepartment())) {
			contractVo.setOperatDepartment(contract.getOperatDepartment());
		}
		if (StringUtils.hasText(contract.getOperator())) {
			contractVo.setOperator(contract.getOperator());
		}
		if (contract.getOperatDate() != null) {
			contractVo.setOperatDate(contract.getOperatDate());
		}
		if (StringUtils.hasText(contract.getMemo())) {
			contractVo.setMemo(contract.getMemo());
		}
		if (StringUtils.hasText(contract.getName())) {
			contractVo.setName(contract.getName());
		}
		if (StringUtils.hasText(contract.getProjectCode())) {
			contractVo.setProjectCode(contract.getProjectCode());
		}
		if (StringUtils.hasText(contract.getRepairCode())) {
			contractVo.setRepairCode(contract.getRepairCode());
		}
		contractVo.setRepairNumber(contract.getRepairNumber());
		if (StringUtils.hasText(contract.getRepairKind())) {
			contractVo.setRepairKind(contract.getRepairKind());
		}
		if (StringUtils.hasText(contract.getRepairKind())) {
			contractVo.setRepairKind(contract.getRepairKind());
		}
		if (contract.getRepairDate() != null) {
			contractVo.setRepairDate(contract.getRepairDate());
		}
		return contractVo;
	}

	
	
	
	
	
	@Override
	public void saveProcessStart(String contractId, String contractType, ProcessInstance pInst) {
		AuditRoot contract = this.getOne(contractId,contractType);
		if (null == pInst || null == contract)
			return;
		// 如果是重新提交审批，删除原来的审批节点
		auditNodeService.getRepository().deleteByPInstId(contract.getProcessInstId());
		contract.setProcessInstId(pInst.getId());
		contract.setAuditState("已提交");
		contract.setStartDate(new Date());

		this.save(contractType, contract);
	}

	@Override
	public void save(String contractType, AuditRoot contract) {
		if (null == contract)
			return;
		switch (contractType) {
		case "备件合同":
			ContractPart contractContractPart=(ContractPart)contract;
			this.getRepository2().save(contractContractPart);
			break;
		case "备泵合同":
			ContractPump contractPump=(ContractPump)contract;
			this.getRepository3().save(contractPump);
			break;
		case "维修合同":
			ContractRepair contractRepair=(ContractRepair)contract;
			this.getRepository4().save(contractRepair);
			break;
		case "项目合同":
			Contract contractMain=(Contract)(contract);
			this.getRepository().save(contractMain);
			break;
		}

	}

	@Override
	public AuditRoot getOne(String id, String contractType) {
		if(!StringUtils.hasText(id) || !StringUtils.hasText(contractType)) return null;
		AuditRoot contract=null;
		switch (contractType) {
		case "备件合同":			
			contract=this.getRepository2().getOne(id);
			break;
		case "备泵合同":			
			contract=this.getRepository3().getOne(id);
			break;
		case "维修合同":		
			contract=this.getRepository4().getOne(id);
			break;
		case "项目合同":			
			contract=this.getRepository().getOne(id);
			break;
		}

		return contract;
	}

	@Override
	public List<ContractInfo> getQueryContractsHql(int start, int length, Map<String, Object> condition, User user,
			String orderName, String dir) {
		@SuppressWarnings("unchecked")
		HashMap<String, Object>numMap=(HashMap<String, Object>)condition.get("numMap");
		Map<String,Object>namedParamsMap=new HashMap<String,Object>();
		StringBuilder hql=queryService.buildCombinedQueryHql("ContractInfo",null, condition, namedParamsMap,null, user);
		for(String key:numMap.keySet()){
			Object value=numMap.get(key);
			if (value instanceof String){
				 if(StringUtils.hasText((String)value)){
					 hql.append("and (e."+key+" like '%"+value.toString()+"%')");
				 }
			}
		}
		String dataFilter=condition.get("dataFilter").toString();
		if(StringUtils.hasText(dataFilter)){
			this.contractDataFilter(hql, dataFilter, user);
		}else{
			return null;
		}
		hql.append(" order by " + orderName + " " + dir);
		Query query=queryService.createQueryHql(hql.toString());
		query.setFirstResult(start).setMaxResults(length);
		return queryService.executeHql(query, namedParamsMap);
	}

	/**数据过滤  
	 * @param hql
	 * @param dataFilter
	 * @param user
	 */
	private void contractDataFilter(StringBuilder hql, String dataFilter, User user){
		if(dataFilter.equals("本部门")){
			hql.append("and (e.superior='"+user.getSaleArea().getSuperior()+"')");
//				.append("and (e.userId='"+user.getId()+"'")
//				.append("or (e.auditState='审批中' or e.auditState='已提交' or e.auditState='通过'))");
		}else if(dataFilter.equals("本片区")){
			hql.append("and (e.superior='"+user.getSaleArea().getSuperior()+"'")
			.append("and e.areaName='"+user.getSaleArea().getAreaName()+"')");
//			.append("and (e.userId='"+user.getId()+"'")
//			.append("or (e.auditState='审批中' or e.auditState='已提交' or e.auditState='通过'))");
//			.append("and (e.auditState!='未提交') and (e.auditState!='驳回')");
//			.append("or (e.userId!='"+user.getId()+"' and e.auditState!='未提交' and e.auditState!='驳回')");
		}else if(dataFilter.equals("本人")){
			hql.append("and (e.userId='"+user.getId()+"')");
		}else if(dataFilter.equals("所有")){
//			hql.append("and (e.userId='"+user.getId()+"')")
//			.append("or (e.userId!='"+user.getId()+"' and e.auditState!='未提交' and e.auditState!='驳回')");
		}
	}

	@Override
	public long getQueryCount(Map<String, String> condition, User user) {
		// TODO Auto-generated method stub
		List<ContractInfo>contractInfos;
		Long count=(long) 0;
		String dataFilter = condition.get("dataFilter");
		if(dataFilter.equals("本部门")){
//			count=contractRepository.
		}
		return 0;
	}

	@Override
	public ContractInfo getDateContractById(String contractId) {
		return contractRepository.getDateThreeContractById(contractId);
	}

	@Override
	public int suspendAndRevocationContractInfo(String contractInfo, String contractType, String type) {
		if(type.equals("撤销")){type="正常";}
		
		if (contractType.equals("项目合同")){
			Contract old = this.getRepository().findOne(contractInfo);
			if (old!=null){
				old.setState(type);
				contractRepository.save(old);
			}
		}else if (contractType.equals("备件合同")){
			ContractPart old = this.getRepository2().findOne(contractInfo);
			if (old!=null){
				old.setState(type);
				contractPartRepository.save(old);
			}
		}else if (contractType.equals("备泵合同")){
			ContractPump old = this.getRepository3().findOne(contractInfo);
			if (old!=null){
				old.setState(type);
				contractPumpRepository.save(old);
			}
		}else if (contractType.equals("维修合同")){
			ContractRepair old = this.getRepository4().findOne(contractInfo);
			if (old!=null){
				old.setState(type);
				contractRepairRepository.save(old);
			}
		}
		return 0;
	}

	@Override
	public String genQuoteDocx(String customerId, User user) {
		String filename = null;
		DecimalFormat df = new DecimalFormat( "###############0.00 ");
		SimpleDateFormat format0 = new SimpleDateFormat("yyyy.MM.dd");
		Customer customer = cusomertRepository.findById(customerId);
		CustomerMailingInfo customerMailingInfo = customerMailingInfoRepository.findByCustomer_IdAndIsDefaultPart(customerId, 1);
		if(customerMailingInfo == null){
			List<CustomerMailingInfo> lists = customerMailingInfoRepository.findByCustomer_IdByUpdateTimeDESC(customerId);
			if(lists.size()>0){
				customerMailingInfo = lists.get(0);
			}
		}
		if (null != customerMailingInfo) {
			Map<String, Object> data = new HashMap<>();
			//Map<String, LinkedList<List<String>>> tablesData = new HashMap<>();
			Map<String, String> textData = new HashMap<>();
			textData.put("username", user.getName());
			textData.put("usertel", user.getContactType());
			textData.put("date", format0.format(new Date()));
			if(customerMailingInfo != null){
				textData.put("customerpeople", customerMailingInfo.getPostDelegate());
				textData.put("customertel", customerMailingInfo.getPostPhone());
				//textData.put("customername", customerMailingInfo.getPostUnit());
				textData.put("customeradress", customerMailingInfo.getPostAddress());
				textData.put("code", customerMailingInfo.getPostZip());
			}/*else{
				textData.put("customerpeople", customer.getcDHDB());
				textData.put("customertel", customer.getcDHPhone());
				textData.put("customeradress", customer.getAddress());
			}*/
			textData.put("customername", customer.getCustomerName());
			data.put("textData", textData);
			//data.put("tablesData", tablesData);
			filename = DocService.genTemplate("邮寄地址.docx", data, "邮寄");
		}/*else{
			filename = "该合同的客户没有邮寄信息，请完善客户邮寄信息。";
		}*/
		return filename;
	}
	
	/*public Contract getContractById(String contractId) {
		return this.contractRepository.getContractById(contractId);
	}*/
}
